package org.xs.object.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    private static StringRedisTemplate stringRedisTemplate;
    @Autowired
    public RedisUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 添加token
     * @param token
     */
    public static void addToken(Integer userId,String token){
        stringRedisTemplate.opsForValue().set(userId.toString(), token, 60 * 60 * 24, TimeUnit.SECONDS);
        //System.out.println("为ID："+userId+"的用户存储token：" + token);
    }

    //删除token
    public static void removeToken(String token){
        //获取用户id
        String userId=ThreadLocatUtil.get();
        stringRedisTemplate.delete(userId);
    }
    //检查 token
    public static boolean checkToken(String token){
        //获取用户id
        String userId=ThreadLocatUtil.get();
        Object tokenResult = stringRedisTemplate.opsForValue().get(userId);
        //String token1= tokenResult.toString();
        //验证token
        if (tokenResult != null && tokenResult.equals(token)){
            return true;
        }
        return false;
    }
}
